package com.mybatis.jpa.SqlProvider;

import com.mybatis.jpa.meta.MetaCell;
import org.apache.ibatis.builder.annotation.ProviderContext;
import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @Author lgt
 * @Date 2017/10/9 : 10:46
 */
public class SelectSqlProvider {

    private static final Logger logger = LoggerFactory.getLogger(SelectSqlProvider.class);

    public String selectByPrimaryKey(Map<String,Object> map, ProviderContext context) {
        Check.notNull(map.get("pk"), "pk must not be null");
        MetaCell meta = ProviderUtil.getMetaCellByMapper(context);
        return new SQL() {{
            SELECT(ProviderUtil.getFieldString(meta));
            FROM(meta.getTableName());
            WHERE(meta.getPrimaryKey() + " = #{pk}");
        }}.toString();
    }

    public String selectByCondition(Condition condition ,ProviderContext context){
        Check.notNull(condition, "condition must not be null");
        MetaCell meta = ProviderUtil.getMetaCellByMapper(context);
        SQL sql = new SQL();
        sql.SELECT(ProviderUtil.getFieldString(meta));
        sql.FROM(meta.getTableName());
        System.out.println(sql.toString() + condition.toString());
        logger.info(" selectByCondition : {} {} ", sql.toString(),condition.toString());
        return sql.toString() + condition.toString();
    }

    public String countByCondition(Condition condition, ProviderContext context) {
        Check.notNull(condition, "condition must not be null");
        MetaCell meta = ProviderUtil.getMetaCellByMapper(context);
        SQL sql = new SQL();
        sql.SELECT("count(1)");
        sql.FROM(meta.getTableName());
        logger.info(" countByCondition : {} {} ", sql.toString(),condition.toString());
        return sql.toString() + condition.toString();
    }

    public String selectAll(ProviderContext context){
        MetaCell meta = ProviderUtil.getMetaCellByMapper(context);
        return new SQL() {{
            SELECT(ProviderUtil.getFieldString(meta));
            FROM(meta.getTableName());
        }}.toString();
    }

    public String countAll(ProviderContext context) {
        MetaCell meta = ProviderUtil.getMetaCellByMapper(context);
        return new SQL() {{
            SELECT("count(1)");
            FROM(meta.getTableName());
        }}.toString();
    }



}
